package zouran.controller;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import zouran.result.ResultMap;
import zouran.service.FileOperationService;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * File Operation Api
 *
 * @author zouran
 * createDate：2024/8/4  0:03
 */
@RequestMapping
@RestController
@Validated
public class FileOperationController {

    private final ResultMap<Object> resultMap;
    private final FileOperationService fileOperationService;

    public FileOperationController(ResultMap<Object> resultMap, FileOperationService fileOperationService) {
        this.resultMap = resultMap;
        this.fileOperationService = fileOperationService;
    }

    /**
     * 获取文件下载链接
     *
     * @param fileName 文件名
     * @return 文件下载地址
     */
    @GetMapping("/cos/get/uri")
    public ResultMap<Object> getCOSFile(@RequestParam("fileName") String fileName) {
        String url = fileOperationService.getFileCosUrl(fileName);
        return resultMap.success(url);
    }

    /**
     * 获取文件上传链接
     *
     * @param fileName     文件名
     * @param earthquakeId 地震编号
     * @param description  文件描述
     * @return 文件上传链接与文件编号
     */
    @RequestMapping("/cos/put/uri")
    public ResultMap<Object> putCOSFile(@RequestParam("fileName") @NotBlank String fileName, @RequestParam("earthquakeId") @Min(0) Long earthquakeId, @RequestParam("description") String description) {
        Map<String, Object> map = fileOperationService.insertFileInfo(earthquakeId, fileName, description);
        return resultMap.success(map);
    }

    /**
     * 更新文件状态
     *
     * @param fileId 文件id
     * @return true or false
     */
    @RequestMapping("/updateFileStatus")
    public ResultMap<Boolean> updateFileStatus(@RequestParam("fileId") Long fileId) {
        return resultMap.success(fileOperationService.updateFileStatus(fileId));
    }

    /**
     * 获取文件列表
     *
     * @param params 必须参数earthquakeId,可选参数page,size,minSize,maxSize,suffix(文件后缀)
     * @return 文件信息列表,{
     * "url":文件名，用于请求/cos/get/uri生成访问链接
     * }
     */
    @RequestMapping("getFileInfoListById")
    public ResultMap<Object> getFileInfoListById(@RequestBody Map params) {
        if (!params.containsKey("earthquakeId")) {
            throw new RuntimeException("缺少必须参数earthquakeId");
        }
        return resultMap.success(fileOperationService.queryFileListById(params));
    }

}
